package com.wr.async.controller;

import com.wr.async.entity.TestEntity;
import com.wr.async.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

@RestController
public class TestController {

    @Autowired
    private TestService service;

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
        service.print();
        System.out.println(Thread.activeCount());
    });

    @RequestMapping("test1")
    public void test1() {
        System.out.println(TestEntity.name);
    }

    @RequestMapping("test")
    public void show() throws InterruptedException, ExecutionException {
        Future<String> show = service.show();
        System.out.println(show.get()+"11");
    }

    @RequestMapping("CompletableFuture")
    public void CompletableFuture() throws InterruptedException, ExecutionException {
        CompletableFuture<String> show1 = service.CompletableFuture();
        CompletableFuture<String> show2 = service.CompletableFuture();
        System.out.println(show1.get()+"1");
        System.out.println(show2.get()+"2");
    }


    // 计数器 实战
    @RequestMapping("count")
    public String count(){
        System.out.println("线程存活数量"+Thread.activeCount());
        System.out.println(Thread.currentThread().getName());
        new Thread(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();
        return "1";
    }





}
